<template>
  <div class="outpatient-manage">
    <Layouts
      :gutter="24"
      :span="[4, 20]"
      :color="['', '#F5F7FA']"
      v-loading="psLoading"
      :rightPadding="'16px'"
      :element-loading-text="loadingText"
    >
      <template #left>
        <!-- <div class="sidebar-tabs">
          <span
            class="tab-btn"
            :class="{ active: activeTab === 'execute' }"
            @click="onActivated('execute')"
            >门诊</span
          >
          <span
            class="tab-btn"
            :class="{ active: activeTab === 'follow' }"
            @click="onActivated('follow')"
            >随访</span
          >
        </div> -->
        <div class="sidebar-tabs">
          <span
            class="tab-btn"
            :class="{ active: activeTab === item.perms }"
            @click="onActivated(item.perms)"
            v-for="(item, index) in menuItem"
          >
            {{ item.menuName }}</span
          >
        </div>
        <div class="patient-container" v-if="activeTab === 'follow'">
          <div class="search-container">
            <el-input
              v-model="patientName"
              placeholder="搜索姓名/电话/身份证/诊号"
              class="search-input"
              clearable
              @input="handleSearch"
              @clear="handleSearch"
            >
            </el-input>

            <!-- <el-select
              v-model="selectedDate"
              placeholder=""
              class="date-select"
              @change="handleSearch"
              :suffix-icon="CaretBottom"
            >
              <el-option label="今天" value="today" />
              <el-option label="昨天" value="yesterday" />
              <el-option label="明天" value="tomorrow" />
            </el-select> -->
            <div
              @click="CustomDatePickerShow = !CustomDatePickerShow"
              class="register-date-box"
            >
              {{ formattedVisitDate }}
              <el-icon size="14">
                <CaretBottom />
              </el-icon>
              <!-- <CaretBottom  size="1" /> -->
            </div>
            <div
              class="register-date-custom-picker"
              v-if="CustomDatePickerShow"
            >
              <DatePickerTime
                @change="CustomDatePickerChange"
                @update:modelValue="CustomDatePickerChange"
                :time="formData.visitDate"
              ></DatePickerTime>
            </div>
          </div>
          <div v-if="followupList.length > 0">
            <div
              v-for="(patient, index) in followupList"
              :key="index"
              @click="onFollowup(patient)"
            >
              <div
                class="user-info—box"
                :class="
                  followupId === patient.followupId ? 'user-info-active' : ''
                "
              >
                <div class="user-info">
                  <div style="display: flex; align-items: center; gap: 5px">
                    <img
                      src="@/assets/outpatient/icon_man_nor.svg"
                      alt="Avatar"
                      class="avatar"
                      v-if="patient.patientGender === '1'"
                    />
                    <img
                      src="@/assets/outpatient/icon_woman_nor.svg"
                      alt="Avatar"
                      class="avatar"
                      v-else-if="patient.patientGender === '2'"
                    />
                    <img
                      class="avatar"
                      src="@/assets/pharmacy/icon_weizhi_nor.png"
                      v-else-if="patient.patientGender === '3'"
                    />

                    <div class="name">{{ patient.patientName }}</div>
                  </div>
                  <div class="status-info">
                    <span
                      class="status-dot"
                      v-if="patient.followupStatus === '1'"
                    ></span>
                    <!-- <span class="status-text">待随访</span> -->
                    <span
                      class="status-text"
                      v-if="patient.followupStatus === '1'"
                      >{{
                        useBaseDataStores.getEnumData(
                          patient.followupStatus,
                          'followUpStatusEnum'
                        )
                      }}</span
                    >
                    <span
                      class="status-text"
                      v-else
                      style="color: rgba(0, 0, 0, 0.2)"
                      >{{
                        useBaseDataStores.getEnumData(
                          patient.followupStatus,
                          'followUpStatusEnum'
                        )
                      }}</span
                    >
                  </div>
                </div>
                <div class="user-info">
                  <div style="display: flex; align-items: center">
                    <div style="width: 22px"></div>

                    <!-- 占位，对齐上面的头像位置 -->
                    <div class="phone-number">{{ patient.visitNo }}</div>
                  </div>
                  <span class="age">
                    {{ dayjs(patient.followupDate).format('MM-DD') }}</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div v-else>
            <el-empty
              description="暂无数据"
              :image="emptyImage"
              :image-size="100"
            />
          </div>
        </div>
        <div class="patient-container" v-if="activeTab === 'execute'">
          <div class="search-container">
            <el-input
              v-model="patientName"
              placeholder="搜索姓名/电话/身份证/诊号"
              class="search-input"
              clearable
              @input="handleSearch"
              @clear="handleSearch"
            >
            </el-input>

            <!-- <el-select
              v-model="selectedDate"
              placeholder="选择日期"
              class="date-select"
              @change="handleSearch"
              :suffix-icon="CaretBottom"
            >
              <el-option label="今天" value="today" />
              <el-option label="昨天" value="yesterday" />
              <el-option label="明天" value="tomorrow" />
            </el-select> -->
            <div
              @click="CustomDatePickerShow = !CustomDatePickerShow"
              class="register-date-box"
            >
              {{ formattedVisitDate }}
              <el-icon size="14">
                <CaretBottom />
              </el-icon>
              <!-- <CaretBottom  size="1" /> -->
            </div>
            <div
              class="register-date-custom-picker"
              v-if="CustomDatePickerShow"
            >
              <DatePickerTime
                @change="CustomDatePickerChange"
                @update:modelValue="CustomDatePickerChange"
                :time="formData.visitDate"
              ></DatePickerTime>
            </div>
          </div>
          <div class="search-container-box">
            <div>
              <div
                v-if="isPlusSign"
                class="user-info—box"
                :class="isPlusSign ? 'user-info-active' : ''"
              >
                <div class="user-info">
                  <div style="display: flex; align-items: center; gap: 5px">
                    <img
                      src="@/assets/outpatient/icon_man_nor.svg"
                      alt="Avatar"
                      class="avatar"
                    />
                    <div class="name">草稿患者</div>
                  </div>
                  <div class="status-info" v-if="isPlusSign">
                    <span class="status-dot"></span>
                    <span class="status-text">待诊</span>
                  </div>
                </div>
                <div class="user-info">
                  <div style="display: flex; align-items: center; gap: 8px">
                    <div style="width: 15px"></div>
                    <!-- 占位，对齐上面的头像位置 -->
                    <div class="phone-number"></div>
                  </div>
                  <span class="age"></span>
                </div>
              </div>
            </div>
            <div v-if="patientList.length > 0">
              <div
                v-for="(patient, index) in patientList"
                :key="index"
                @click="
                  onUserInfo(
                    patient.patientId,
                    patient.medicalId,
                    patient.visitStatus
                  )
                "
              >
                <div
                  class="user-info—box"
                  :class="
                    medicalId === patient.medicalId ? 'user-info-active' : ''
                  "
                >
                  <div class="user-info">
                    <div style="display: flex; align-items: center; gap: 5px">
                      <img
                        src="@/assets/outpatient/icon_man_nor.svg"
                        alt="Avatar"
                        class="avatar"
                        v-if="patient.patientGender === '1'"
                      />
                      <img
                        src="@/assets/outpatient/icon_woman_nor.svg"
                        alt="Avatar"
                        class="avatar"
                        v-if="patient.patientGender === '2'"
                      />
                      <img
                        class="avatar"
                        src="@/assets/pharmacy/icon_weizhi_nor.png"
                        v-else-if="patient.patientGender === '3'"
                      />
                      <div class="name">{{ patient.patientName }}</div>
                    </div>
                    <div class="status-info">
                      <span
                        class="status-dot"
                        v-if="patient.visitStatus == '1'"
                      ></span>
                      <span
                        class="status-text"
                        v-if="patient.visitStatus === '1'"
                        >{{
                          useBaseDataStores.getEnumData(
                            patient.visitStatus,
                            'visitStatusEnum'
                          )
                        }}</span
                      >
                      <span
                        class="status-text"
                        v-else
                        style="color: rgba(0, 0, 0, 0.2)"
                        >{{
                          useBaseDataStores.getEnumData(
                            patient.visitStatus,
                            'visitStatusEnum'
                          )
                        }}</span
                      >
                    </div>
                  </div>
                  <div class="user-info">
                    <div style="display: flex; align-items: center; gap: 8px">
                      <div style="width: 15px"></div>
                      <!-- 占位，对齐上面的头像位置 -->
                      <div class="phone-number">{{ patient.visitNo }}</div>
                    </div>
                    <span class="age">{{
                      dayjs(patient.visitDate).format('MM-DD')
                    }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div
              v-else
              style="
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100%;
              "
            >
              <el-empty
                description="暂无数据"
                :image="emptyImage"
                :image-size="100"
              />
            </div>
          </div>
          <div>
            <ToolboxCard @onToolboxs="onToolboxs" @onPlusSign="onPlusSign" />
          </div>
        </div>
      </template>
      <template #right>
        <div
          v-if="activeTab === 'follow' && patientId"
          style="
            display: flex;
            justify-content: space-between;
            height: 100%;
            width: 100%;
          "
        >
          <div
            style="
              height: 100%;
              width: 100%;
              padding-right: 16px;
              overflow: auto;
            "
          >
            <div class="recent-visit">
              <el-button
                class="edit-button"
                type="primary"
                @click="saveFollow()"
                >保存</el-button
              >
            </div>
            <patient-user :patientDetail="followDetail" />
            <patientInfo
              :patientDetail="followDetail"
              style="margin-top: 10px"
            />
            <FollowUpForm
              :patientDetail="followDetail"
              style="margin-top: 10px"
              ref="followUpFormRef"
            />
          </div>
          <div>
            <flollowRecording
              :patientId="patientId"
              :historyList="followupRecordList"
              @onCopys="onCopys"
            />
          </div>
        </div>
        <!-- {{activeTab}}{{patientId}} -->
        <div
          v-if="(activeTab === 'execute' && patientId) || isPlusSign"
          style="
            display: flex;
            justify-content: space-between;
            height: 100%;
            width: 100%;
          "
        >
          <div
            style="
              padding-right: 16px;
              width: 100%;
              height: 100%;
              overflow: auto;
            "
          >
            <div style="width: 100%; height: 100%">
              <!-- 患者信息表单条 -->
              <div class="patient-info-bar-1">
                <div style="display: flex; align-items: center">
                  <div class="patient-info-bar">
                    <img
                      src="@/assets/outpatient/icon_man_nor.svg"
                      alt="Avatar"
                    />
                    <el-input
                      v-model="medicalList.patientName"
                      placeholder="请输入"
                      class="info-input name-input"
                      @input="onPatientName"
                      :disabled="isEdit"
                    />
                    <div class="divider"></div>
                    <span class="unit" v-if="medicalList.patientGender === '1'"
                      >男</span
                    >
                    <span
                      class="unit"
                      v-else-if="medicalList.patientGender === '2'"
                      >女</span
                    >
                    <span class="unit" v-else>未知</span>
                    <img
                      style="cursor: pointer"
                      src="@/assets/icon/Group_1321317125.svg"
                      alt=""
                      @click="onAcupoint"
                      v-if="!isEdit"
                    />
                    <div class="divider"></div>
                    <span class="unit">
                      <el-input
                        v-model="medicalList.patientPhone"
                        placeholder="请输入"
                        class="info-input"
                        style="width: 110px"
                        :disabled="isEdit"
                      />
                    </span>

                    <!-- <el-icon
                  class="selector-icon"
                  size="16"
                  @click="onAcupoint"
                  style="cursor: pointer"
                >
                  <Star />
                </el-icon> -->
                    <div class="divider"></div>

                    <el-input-number
                      :controls="false"
                      v-model="medicalList.ageYear"
                      placeholder="请输入"
                      :disabled="isEdits"
                      class="info-input age-input"
                    />
                    <span class="unit">岁</span>
                    <el-input-number
                      :controls="false"
                      v-model="medicalList.ageMonth"
                      placeholder="请输入"
                      :disabled="isEdits"
                      class="info-input month-input"
                    />
                    <span class="unit">月</span>
                    <div class="divider"></div>
                    <el-input
                      v-model="medicalList.weight"
                      placeholder="请输入"
                      :disabled="isEdits"
                      class="info-input weight-input"
                    >
                      <template #suffix>kg</template>
                    </el-input>
                    <div class="divider"></div>
                    <el-input
                      v-model="medicalList.systolicBp"
                      placeholder="请输入"
                      class="info-input bp-input"
                      :disabled="isEdits"
                      style="width: 70px"
                    >
                      <template #suffix>/</template>
                    </el-input>
                    <el-input
                      v-model="medicalList.diastolicBp"
                      placeholder="请输入"
                      class="info-input bp-input"
                      style="width: 100px"
                      :disabled="isEdits"
                    >
                      <template #suffix>mmHg</template>
                    </el-input>
                  </div>
                  <img
                    v-if="isPlusSign"
                    style="cursor: pointer; margin-left: 10px"
                    src="@/assets/icon/icon_qingkong_nor.svg"
                    alt=""
                    @click="onClearPatientInfo"
                  />
                </div>

                <userSelect
                  v-if="isPlusSign && medicalList.patientName"
                  ref="userSelectDom"
                  @select="handleSelect1"
                >
                </userSelect>
                <div class="btn-group" v-if="medicalList.visitStatus === '1'">
                  <el-button @click="onCompletePreDiagnosis()"
                    >完成预诊</el-button
                  >
                  <el-button type="primary" @click="onReceivingPatients()"
                    >完成接诊</el-button
                  >
                  <!-- <el-button @click="onCancel()">取消</el-button> -->
                </div>
                <div class="btn-group" v-if="medicalList.visitStatus === '2'">
                  <el-button
                    @click="onCompletePreDiagnosisEdit()"
                    type="primary"
                    v-if="visitStatus == '1'"
                    >保存</el-button
                  >
                  <el-button @click="onEdit" type="primary" v-else
                    >编辑</el-button
                  >
                  <el-button
                    v-if="visitStatus == '1'"
                    @click="
                      visitStatus = '2';
                      isEdit = true;
                      isEdits = true;
                    "
                    >取消</el-button
                  >
                  <el-button @click="onPrint">打印</el-button>
                </div>
              </div>
              <!-- 病历 -->
              <outpatient
                :patientId="patientId"
                :patientDetail="patientDetail"
                :fieldList="medicalList?.fieldList || []"
                activeName_1="1"
                :doctorAdvice="medicalList.doctorAdvice"
                style="width: 100%"
                ref="outpatientRef"
                :visitStatus="visitStatus"
                @doctorAdvice="ondoctorAdvice"
                @loadingFalseFun="loadingFalseFun"
              />

              <!-- 查验项目 -->
              <InspectionTable
                :patientId="patientId"
                :onZS="onZS"
                :frequencyOptions="frequency"
                :patientDetail="patientDetail"
                :tableData="medicalList?.examList || []"
                style="margin-top: 10px"
                :visitStatus="visitStatus"
                ref="inspectionTableRef"
              />
              <!-- 处方医嘱  模板 -->
              <div class="header-section-1">
                <h3>处方医嘱</h3>
                <div class="action-buttons" v-if="visitStatus != '2'">
                  <el-button type="primary" plain @click="setActiveType('1')">
                    成药处方
                  </el-button>
                  <el-button type="primary" plain @click="setActiveType('3')">
                    中药处方
                  </el-button>
                  <el-button type="primary" plain @click="setActiveType('2')">
                    输液处方
                  </el-button>
                  <el-button type="primary" plain @click="setActiveType('4')">
                    外治处方
                  </el-button>
                  <!-- <span style="padding: 0 10px; color: #dcdcdc">|</span> -->
                  <div class="line" style="margin-left: 10px"></div>
                  <el-button plain @click="onSelectTemplate()">
                    选择模板
                  </el-button>
                  <el-button plain @click="onSave('3')"> 存模板 </el-button>
                </div>
              </div>
              <div
                class="prescription-template"
                v-for="(item, index) in medicalList?.rxList || []"
              >
                <div v-if="item.rxType === '1'">
                  <!-- 成药处方一 -->
                  <prescription
                    :prescriptionData="item"
                    :frequencyOptions="frequency"
                    :weight="medicalList.weight"
                    :uuid="item.uuid"
                    :onZS="onZS"
                    ref="prescriptionRef"
                    :displayNowUUid="displayNowUUid"
                    @searchKeyboard="onSearchKeyboard(item.uuid)"
                    :visitStatus="visitStatus"
                    @removeRow="(result: any) => removeRow(result, index)"
                  />
                </div>
                <div v-if="item.rxType === '2'">
                  <!-- 输液处方四 -->
                  <transfusion
                    :onZS="onZS"
                    :weight="medicalList.weight"
                    :group="item"
                    :displayNowUUid2="displayNowUUid"
                    @searchKeyboard="onSearchKeyboard(item.uuid)"
                    :visitStatus="visitStatus"
                    @addNewRow="(result: any) => addNewRow(result, index)"
                    @removeRow="(result: any) => removeRow(result, index)"
                    ref="transfusionRef"
                  />
                </div>
                <div v-if="item.rxType === '3'">
                  <!-- 中药处方二 -->
                  <medicinalHerb
                    :medicinalHerbData="item"
                    :visitStatus="visitStatus"
                    ref="medicinalHerbRef"
                    :displayNowUUid2="displayNowUUid"
                    @searchKeyboard="onSearchKeyboard(item.uuid)"
                    @removeRow="(result: any) => removeRow(result, index)"
                  ></medicinalHerb>
                </div>
                <div v-if="item.rxType === '4'">
                  <!-- 外治处方三 -->
                  <ExternalTreatment
                    ref="externalTreatmentRef"
                    :onZS="onZS"
                    :visitStatus="visitStatus"
                    :externalTreatment="item"
                    @removeRow="(result: any) => removeRow(result, index)"
                  ></ExternalTreatment>
                </div>
              </div>
              <div class="followup-box">
                <div class="followup-row">
                  <div class="followup-label">是否随访</div>
                  <div class="followup-content" v-if="visitStatus != '2'">
                    <div class="visit-options">
                      <el-radio-group v-model="medicalList.isFollowUp">
                        <el-radio value="0" size="large">不随访</el-radio>
                        <el-radio value="1" size="large">随访</el-radio>
                      </el-radio-group>
                      <span v-if="medicalList.isFollowUp == '1'">
                        <el-input-number
                          v-model="medicalList.followUpDays"
                          placeholder="请输入"
                          class="search-input"
                          clearable
                          :controls="false"
                          :min="0"
                          :max="999"
                          style="width: 100px; margin-left: 20px"
                        >
                        </el-input-number>
                        天后随访
                      </span>
                    </div>
                  </div>
                  <div v-else class="followup-content">
                    <span v-if="medicalList.isFollowUp == '0'">不随访</span>
                    <span v-else>随访</span>
                    {{ medicalList.followUpDays }}
                    <span v-if="medicalList.isFollowUp == '1'">天后随访</span>
                  </div>
                </div>
                <div class="followup-row">
                  <div class="followup-label">医嘱事项</div>
                  <div class="followup-content">
                    <div class="advice-input">
                      <DoctorAdviceSelect
                        v-model="medicalList.doctorAdvice"
                        :multi-line="true"
                        :toggle-selected="true"
                        v-if="visitStatus != '2'"
                      />
                      <span
                        v-else
                        v-html="
                          medicalList.doctorAdvice
                            ? medicalList.doctorAdvice.replace(/\n/g, '<br>')
                            : ''
                        "
                      ></span>
                    </div>
                  </div>
                </div>
              </div>
              <div style="height: 100px"></div>
            </div>
          </div>
          <div>
            <member-card
              @onCopyIntm="onCopyIntm"
              @onCopyIntm1="onCopyIntm1"
              :patientId="patientId"
              @onPrint1="onPrint1"
              :patientName="medicalList.patientName"
              ref="memberCardRef"
              :historyList="followupRecordList"
            />
          </div>
          <!-- 选择模板 -->
          <el-dialog
            v-model="isTemplate"
            class="custom-transition-dialog-2"
            :title="''"
            :width="1500"
            top="5vh"
            @close="isTemplate = false"
          >
            <template
              #header="{ close, titleId, titleClass }"
              style="display: none"
            >
              <div class="my-header" style="display: none">
                <el-icon class="el-icon--left">
                  <CircleCloseFilled />
                </el-icon>
              </div>
            </template>
            <!-- 1是病历模板 2是检验模板 3是处方模板 -->
            <managePages
              :medicalList="[]"
              @updataTemplate="updataTemplate"
              :activeName_s="'3'"
            />
          </el-dialog>
          <!-- 保存模板 -->
          <addTemplate
            ref="addTemplateRef"
            @addTemplate="onAddTemplate"
          ></addTemplate>
          <!-- 门诊完成药品冲突弹框 -->
          <el-dialog
            v-model="isMedical"
            :title="'异常提示'"
            :width="800"
            @close="isMedical = false"
          >
            <div class="risk-dialog-body">
              <template v-if="riskList.length > 0">
                <div
                  v-for="(risk, idx) in riskList"
                  :key="idx"
                  class="risk-item"
                >
                  <el-icon class="risk-icon">
                    <WarningFilled />
                  </el-icon>
                  <div class="risk-text" v-html="risk"></div>
                </div>
              </template>
              <template v-else>
                <div class="risk-empty">暂无风险提示</div>
              </template>
            </div>
            <template #footer>
              <el-button type="primary" @click="handleSubmit"
                >继续提交</el-button
              >
              <el-button @click="isMedical = false">取消</el-button>
            </template>
          </el-dialog>
        </div>
        <span>
          <div
            v-if="activeTab === 'follow' && !patientId"
            style="
              height: 100%;
              margin: 0px auto;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <el-empty
              description="暂无数据"
              :image="emptyImage"
              :image-size="260"
            />
          </div>
          <div
            v-if="(activeTab === 'execute' && !patientId) && !isPlusSign"
            style="
              height: 100%;
              margin: 0px auto;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <el-empty
              description="暂无数据"
              :image="emptyImage"
              :image-size="260"
            />
          </div>
        </span>
      </template>
    </Layouts>
    <patientUpdata ref="patientUpdataRef" />
    <BottomDrawer
      :visible="callDialog"
      :title="'挂号'"
      :width="450"
      @close="callDialog = false"
    >
      <CallDialog
        v-if="callDialog"
        :visitDate="formData.visitDate"
        :visible="callDialog"
      />
    </BottomDrawer>
    <BottomDrawer
      :visible="visiblePrint"
      :title="'打印'"
      :width="350"
      :top="'30vh'"
      :showFooter="false"
      @close="visiblePrint = false"
    >
      <div>
        <div class="printBtn" @click="printBox">病历</div>
      </div>
      <div style="margin-top: 10px">
        <div class="printBtn" @click="printBox1">查验单</div>
      </div>
      <div style="margin-top: 10px">
        <div class="printBtn" @click="printBox2">处方</div>
      </div>
    </BottomDrawer>
    <el-dialog
      v-model="isAdmissions"
      :width="400"
      @close="isAdmissions = false"
    >
      <template #title>
        <span style="display: inline-flex; align-items: center">
          <img src="@/assets/icon/info-circle-filled.svg" alt="" />
          <span style="margin-left: 10px">完成接诊？</span>
        </span>
      </template>
      <div style="padding: 0px 30px">
        <div class="">是否确定完成诊断？</div>
        <div style="margin-top: 10px">
          <el-checkbox-group v-model="AdmissionsList" class="checkbox-grid">
            <el-checkbox label="打印病历" :value="1" />
            <el-checkbox label="打印检查单" :value="2"></el-checkbox>
            <el-checkbox label="打印处方" :value="3"></el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <!-- <template #footer>
        <el-button @click="isAdmissions = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit1">确认</el-button>
      </template> -->
      <template #footer>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-checkbox-group v-model="Recording" class="checkbox-grid">
              <el-checkbox label="下载录音文件" :value="1" />
            </el-checkbox-group>
          </div>
          <div>
            <el-button @click="isAdmissions = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit1">确认</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="isAdmissionsEdit"
      :width="400"
      @close="isAdmissionsEdit = false"
    >
      <template #title>
        <span style="display: inline-flex; align-items: center">
          <img src="@/assets/icon/info-circle-filled.svg" alt="" />
          <span style="margin-left: 10px">编辑完成？</span>
        </span>
      </template>
      <div style="padding: 0px 30px">
        <div class="">是否确定完成编辑？</div>
        <div style="margin-top: 10px">
          <el-checkbox-group v-model="AdmissionsList" class="checkbox-grid">
            <el-checkbox label="打印病历" :value="1" />
            <el-checkbox label="打印检查单" :value="2"></el-checkbox>
            <el-checkbox label="打印处方" :value="3"></el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <template #footer>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-checkbox-group v-model="Recording" class="checkbox-grid">
              <el-checkbox label="下载录音文件" :value="1" />
            </el-checkbox-group>
          </div>
          <div>
            <el-button @click="isAdmissionsEdit = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit2">确认</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <div style="display: none">
      <medicalRecordPrint
        :info="MedicalPrintinfo"
        ref="medicalRecordPrintRef"
        @onCancel="visiblePrint = false"
      >
      </medicalRecordPrint>
    </div>
    <div style="display: none">
      <inspectPrint
        :info="inspectPrintInfo"
        ref="inspectPrintRef"
        @onCancel="visiblePrint = false"
      ></inspectPrint>
    </div>
    <div
      v-for="value in PrescriptionPrintInfo?.rxList || []"
      style="display: none"
    >
      <!-- 成药 -->
      <PatentMedicinePrint
        :info="value"
        :uuid="value.uuid"
        :groupList="value || []"
        v-if="value.rxType == '1'"
        :ref="
          (el) => {
            if (el) componentRefs[value.uuid] = el;
          }
        "
        @onCancel="visiblePrint = false"
      ></PatentMedicinePrint>
      <!-- 输液 -->
      <transfusionPrint
        :info="value"
        :uuid="value.uuid"
        :groupList="value || []"
        v-if="value.rxType == '2'"
        :ref="
          (el) => {
            if (el) componentRefs[value.uuid] = el;
          }
        "
        @onCancel="visiblePrint = false"
      ></transfusionPrint>
      <!-- 中药 -->
      <medicinalHerbPrint
        :info="value"
        :uuid="value.uuid"
        :groupList="value || []"
        v-if="value.rxType == '3'"
        :ref="
          (el) => {
            if (el) componentRefs[value.uuid] = el;
          }
        "
        @onCancel="visiblePrint = false"
      ></medicinalHerbPrint>
      <!-- 外治 -->
      <ExternalTreatmentPrint
        :info="value"
        :uuid="value.uuid"
        :groupList="value || []"
        v-if="value.rxType == '4'"
        :ref="
          (el) => {
            if (el) componentRefs[value.uuid] = el;
          }
        "
        @onCancel="visiblePrint = false"
      ></ExternalTreatmentPrint>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeUnmount } from 'vue';
import DoctorAdviceSelect from '@/components/DoctorAdviceSelect.vue';
import emptyImage from '@/assets/icon/internet_empty_illustration.svg';
import { v4 as uuidv4 } from 'uuid';
import medicalRecordPrint from './common/medicalRecordPrint.vue';
import PatentMedicinePrint from './common/PatentMedicinePrint.vue';
import transfusionPrint from './common/transfusionPrint.vue';
import ExternalTreatmentPrint from './common/ExternalTreatmentPrint.vue';
import medicinalHerbPrint from './common/medicinalHerbPrint.vue';
import inspectPrint from './common/inspectPrint.vue';
import userSelect from './common/userSelect.vue';
import dayjs from 'dayjs';
import { printMultiple } from '@/utils/print';
import {
  getMedicalList,
  getFollowupList,
  getFollowupRecordList,
  getMedicalDetail,
  completePreDiagnosis,
  completeInquiry,
  drugConflictCheck,
  getFollowupDetail,
  updateMedicalRecord,
  completeFollowup,
  printMedicalRecord,
  printExam,
  printPrescription,
} from '@/api/medical';
import { CaretBottom, WarningFilled, Warning } from '@element-plus/icons-vue';
import PatientUser from './common/patientUser.vue';
import { CircleCloseFilled } from '@element-plus/icons-vue';
import MemberCard from './common/memberCard.vue';
import addTemplate from './common/addTemplate.vue';
import patientUpdata from './common/patientUpdata.vue';
import managePages from './common/managePages.vue';
import patientInfo from './common/patientInfo.vue';
import outpatient from './common/outpatient.vue';
import InspectionTable from './common/InspectionTable.vue';
import medicinalHerb from './common/medicinalHerb.vue';
import ExternalTreatment from './common/ExternalTreatment.vue';
import flollowRecording from './common/flollowRecording.vue';
import transfusion from './common/transfusion.vue';
import prescription from './common/prescription.vue';
import { getDeliveryHistoryList, getDispenseHistoryList } from '@/api/pharmacy';
import {
  getPatientList,
  getPatientDetail,
  getPatientMedicalField,
} from '@/api/patient';
import type {
  PatientInfo,
  PatientDetail,
  RechargeOrderListData,
  RechargeOrderQueryParams,
} from '@/types/patient';
import FollowUpForm from './common/followUpForm.vue';
import store from '@/store';
import {
  addTemplateMedical,
  addTemplatePrescription,
  addTemplateInspection,
} from '@/api/formwork';
const psLoading = ref<boolean>(false);
const useBaseDataStores = store.useBaseDataStore();
const storageList = ref<any[]>(useBaseDataStores.Storage);
const formData = ref<any>({
  visitDate: dayjs(new Date()).format('YYYY-MM-DD'),
});
const frequency = ref(useBaseDataStores.getDictsSelect('FREQUENCY'));
const medicalFieldStore = store.useMedicalRecordFieldStore();
const ispatientData = ref({});
const isPlusSign = ref(false); // 是否显示草稿患者
const patientUpdataRef = ref<InstanceType<typeof patientUpdata>>();
const followUpFormRef = ref<InstanceType<typeof FollowUpForm>>();
const addTemplateRef = ref<InstanceType<typeof addTemplate> | null>(null);
const userSelectDom = ref<InstanceType<typeof userSelect> | null>(null);
const memberCardRef = ref<InstanceType<typeof MemberCard> | null>(null);
const medicinalHerbPrintRef = ref<InstanceType<
  typeof medicinalHerbPrint
> | null>(null);
const transfusionPrintRef = ref<InstanceType<typeof transfusionPrint> | null>(
  null
);
const ExternalTreatmentPrintRef = ref<InstanceType<
  typeof ExternalTreatmentPrint
> | null>(null);
const patientList = ref<any[]>([]); // 患者列表
const followupList = ref<any[]>([]); // 随访列表
const MedicalPrintinfo = ref<any>({}); //病历打印数据
const inspectPrintInfo = ref<any>({}); //检验打印数据
const Recording = ref<any>([]);
const displayNowUUid = ref('');
const PrescriptionPrintInfo = ref<any>({}); //处方打印数据
const CustomDatePickerShow = ref(false);
const isAdmissions = ref(false);
const activeTab = ref('execute'); // tab状态
const templateDialog = ref(false); // 病历模板弹窗
const followupId = ref<number | null>(null); // 当前选中的随访ID
const visiblePrint = ref(false);
const medicalRecordPrintRef = ref<InstanceType<
  typeof medicalRecordPrint
> | null>(null);
const inspectPrintRef = ref<InstanceType<typeof inspectPrint> | null>(null);
const PatentMedicinePrintRef = ref<InstanceType<
  typeof PatentMedicinePrint
> | null>(null);
const ZSValue = ref(''); // 主诉
// 搜索和筛选
const patientName = ref('');
const selectedDate = ref('today');
const patientDetail = ref<PatientDetail | undefined>(undefined); // 当前选中的患者详情
const followDetail = ref<any>({}); // 随访详情
const medicalList = ref<any>({
  isFollowUp: '1',
}); //病历详情
const isTemplate = ref(false); // 选择模板弹窗
const isMedical = ref(false); // 保存模板弹窗
const route = useRoute();
const visitStatus = ref('');
// 风险提示列表（可由后端校验结果赋值，支持富文本片段）
const riskList = ref<string[]>([]);
const followList = ref<any[]>([]); // 随访列表
const pageNo = ref(1);
const pageSize = ref(10);
const dispenseHistoryList = ref<any[]>([]);
const AdmissionsList = ref<any[]>([1]);
const callDialog = ref<boolean>(false);
const patientId = ref<number | null>(null); // 当前选中的患者ID
const outpatientRef = ref<InstanceType<typeof outpatient>>(); // 病历的ref获取病历模板数据
const inspectionTableRef = ref<InstanceType<typeof InspectionTable>>(); // 检验项目的ref获取检验项目数据
// 这些组件在 v-for 中使用了相同的 template ref 名称，Vue 会将它们收集为“数组模板引用”
const prescriptionRef = ref<InstanceType<typeof prescription>[]>([]); // 处方（数组）
const transfusionRef = ref<InstanceType<typeof transfusion>[]>([]); // 输液（数组）
const medicinalHerbRef = ref<InstanceType<typeof medicinalHerb>[]>([]); // 中药（数组）
const externalTreatmentRef = ref<InstanceType<typeof ExternalTreatment>[]>([]); // 外治处方（数组）
const medicalId = ref<number | null>(null); // 当前选中的病历ID
const handleClick = (tab: any, event: Event) => {
  //console.log(tab, event);
};
let menuList = ref<any>(
  await store.useBaseDataStore().findMenuList(route.query.menuId)
);
let menuItem = ref<any>(
  menuList.value.filter((item: any) => item.menuType == 2)
);
//console.log(menuItem.value);

if (menuItem.value.length > 0) {
  activeTab.value = menuItem.value[0].perms; // 默认选中标签
}
const form = ref({
  name: '',
  gender: '男',
  age: '',
  month: '',
  weight: '',
  bloodPressure: '',
});
const followupRecordList = ref<any[]>([]); // 随访记录列表
const onUserInfo = async (id: any, medical: any, visitStatus1: any) => {
  // 这里可以添加跳转到患者详情页面的逻辑
  medicalId.value = medical;
  isPlusSign.value = false;
  isEdit.value = true;
  //console.log(visitStatus1);

  if (visitStatus1 == '1') {
    visitStatus.value = '1';
    isEdits.value = false;
  } else {
    visitStatus.value = '2';
    isEdits.value = true;
  }
  console.log(id, medical, visitStatus1);
  patientId.value = id; // 设置当前选中的患者ID

  // 获取患者详情
  const data = await getPatientDetail({ patientId: id });
  patientDetail.value = data.data; // 更新患者详情
  getMedicalDetailData(); // 获取病历详情
};
const componentRefs = ref<any>({});
const formatDate = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD');
};
const loadingText = ref('正在加载设备...');
const loadingFalseFun = (e: any, text: any) => {
  psLoading.value = e;
  loadingText.value = text;
};
const onAcupoint = () => {
  if (medicalList.value.patientGender === '1') {
    medicalList.value.patientGender = '2';
  } else {
    medicalList.value.patientGender = '1';
  }
};
const CustomDatePickerChange = (date: any) => {
  // 为空直接关闭
  if (!date) {
    CustomDatePickerShow.value = false;
    return;
  }

  // 规范化为 YYYY-MM-DD 字符串
  const next = dayjs(date).isValid()
    ? dayjs(date).format('YYYY-MM-DD')
    : String(date);
  formData.value.visitDate = next;
  if (activeTab.value === 'execute') {
    getMedicalListData();
  } else {
    getFollowupListData();
  }
  patientId.value = null;
  CustomDatePickerShow.value = false;
  isPlusSign.value = false;
  medicalId.value = null;
};
const onFollowup = async (patient: any) => {
  followupId.value = patient.followupId; // 获取患者ID
  patientId.value = patient.patientId; // 设置当前选中的患者ID
  ispatientData.value = patient;
  followupRecord(); // 获取患者随访记录
  followupRecordDdta();
};
// 获取患者随访记录
const followupRecordDdta = async () => {
  const data = await getFollowupDetail({
    followupId: followupId.value,
  });
  if (data.code != '200') {
    //ElMessage.error(data.msg);
    return;
  }
  followDetail.value = data.data;
};
const onActivated = async (value: string) => {
  activeTab.value = value;
  patientId.value = null;
  isPlusSign.value = false;
  if (value === 'execute') {
    getMedicalListData();
  } else {
    getFollowupListData();
  }
};
const onEdit = () => {
  visitStatus.value = '1';
  isEdit.value = true;
  isEdits.value = false;
};

// 添加处方
const addNewRow = (group?: any, index?: any) => {
  const num = index + 1;
  //console.log(group);

  const data = {
    groupList: [
      {
        groupName: '第一组',
        usageCode: 'JMDZ',
        usageCodeText: '静脉滴注',
        frequencyCode: 'qd',
        frequencyCodeText: '1天1次',
        frequencyTimes: 1,
        cycle: 1,
        cycleUnit: 'day',
        cycleUnitText: '天',
        ivDripRate: '50',
        subtotal: 1000,
        uuid: uuidv4(),
        detailList: [],
      },
    ],
    rxType: '2',
    rxName: '输注处方' + toChineseNumber(num),
    totalAmount: 0,
    uuid: uuidv4(), // 唯一标识
    storageId: storageList.value.find((item) => item.isDefault == 1)?.storageId,
  };
  medicalList.value.rxList = (medicalList.value.rxList || []).concat(data);
  ElMessage.success('添加成功');
};
// 删除处方
const removeRow = (group?: any, index?: any) => {
  medicalList.value.rxList.splice(index, 1);
  ElMessage.success('处方已删除');
};
const today = computed(() => {
  const date = new Date();
  return date.toISOString().split('T')[0]; // YYYY-MM-DD格式
});
// 获取病历详情
const getMedicalDetailData = async () => {
  if (patientId.value) {
    const data = await getMedicalDetail({ medicalId: medicalId.value });
    if (data.code != '200') {
      //ElMessage.error(data.msg);
      return;
    }
    data.data.rxList.forEach((element: { uuid: string }) => {
      element.uuid = uuidv4(); // 为每个处方生成唯一标识符
    });
    medicalList.value = data.data;
    // 修改血压值的赋值逻辑，增加空值判断
    medicalList.value.systolicName =
      (medicalList.value.systolicBp ? medicalList.value.systolicBp : '') +
      '/' +
      (medicalList.value.diastolicBp ? medicalList.value.diastolicBp : '');
    //console.log(medicalList.value);
  }
};
// 接诊
const onPlusSign = async () => {
  // x选择患者弹窗
  isPlusSign.value = true;
  isEdit.value = false;
  isEdits.value = false;
  const data = {
    patientName: '',
    pageNo: 1,
    pageSize: 1000000,
  };
  patientId.value = null;
  medicalId.value = null;
  medicalList.value.visitStatus = '1';
  visitStatus.value = '1';
  medicalList.value.fieldList = [];
  medicalList.value.examList = [];
  medicalList.value.rxList = [];
  medicalList.value.isFollowUp = '0';
  medicalList.value.doctorAdvice = '';
  medicalList.value.followUpDays = null;
  medicalList.value.ageYear = null;
  medicalList.value.patientName = '';
  medicalList.value.patientGender = '1';
  medicalList.value.weight = null;
  medicalList.value.systolicName = '';
  medicalList.value.ageMonth = null;
  medicalList.value.diastolicBp = null;
  medicalList.value.patientPhone = null;
  medicalList.value.systolicBp = null;
  // const response = await getPatientList(data);
  // if (response && response.data) {
  //   // patientList.value = response.data;
  //   activeTab.value = 'execute';
  //   userSelectDom.value?.open(response.data);
  // }
};
const onPatientName = async (value: string) => {
  const data = {
    patientName: value,
    pageNo: 1,
    pageSize: 1000000,
  };
  const response = await getPatientList(data);
  if (response.code == '200') {
    // patientList.value = response.data;
    activeTab.value = 'execute';
    nextTick(() => {
      userSelectDom.value?.open(response.data);
    });
  } else {
    medicalList.value.patientId = null;
    medicalList.value.medicalId = null;
  }
};
const tomorrow = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  return date.toISOString().split('T')[0];
});

const onToolboxs = () => {
  //console.log('叫号');
  callDialog.value = true;
  // 打开叫号弹窗的逻辑
  // 这里可以添加打开叫号弹窗的代码
};

const groupedAndRenamedRxList = () => {
  // 1. 按 rxType 分组
  const groupedMap = medicalList.value.rxList.reduce((acc: any, item: any) => {
    if (!acc[item.rxType]) {
      acc[item.rxType] = [];
    }
    if (item && item.rxType != null) {
      acc[item?.rxType].push(JSON.parse(JSON.stringify(item)));
    }
    return acc;
  }, {} as Record<string, any[]>);

  // 2. 遍历分组，重新命名 rxName
  const result: any[] = [];
  Object.entries(groupedMap).forEach(([rxType, items]: any) => {
    items.forEach((item: { rxName: string }, index: number) => {
      item.rxName = `${rxType}药品${index + 1}`; // 重新命名，如 "A类药品1", "A类药品2"
      result.push(item);
    });
  });

  return result;
};
// 数字改成中文
const toChineseNumber = (num: number) => {
  const cnNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const cnUnits = ['', '十', '百', '千', '万'];
  if (num < 10) return cnNums[num];
  if (num < 20) return '十' + (num === 10 ? '' : cnNums[num % 10]);
  if (num < 100) {
    const ten = Math.floor(num / 10);
    const unit = num % 10;
    return cnNums[ten] + '十' + (unit === 0 ? '' : cnNums[unit]);
  }
  // 这里只处理到99，更多位数可扩展
  return num;
};
function renameRxList(list: Array<{ rxType: string | number }>) {
  const typeNames: Record<string, string> = {
    '1': '中西成药处方',
    '2': '输注处方',
    '3': '中药处方',
    '4': '外治处方',
  };

  const typeCount: Record<string, number> = {};

  return list.map((item) => {
    const type = String(item.rxType);

    if (!typeCount[type]) typeCount[type] = 0;
    typeCount[type] += 1;

    const typeName = typeNames[type] || '未知处方';
    const chineseNum = toChineseNumber(typeCount[type]);

    return {
      ...item,
      rxName: `${typeName}${chineseNum}`,
    };
  });
}
const onCopyIntm = (data: any) => {
  if (data.rxList.length > 0) {
    data.rxList.forEach((element: any) => {
      delete element.rxId;
      delete element.payStatus;
    });
  }
  if (data.examList.length > 0) {
    data.examList.forEach((element: any) => {
      delete element.examId;
      delete element.payStatus;
    });
  }
  const fields = outpatientRef.value?.fields;
  if (medicalList.value.fieldList.length == 0) {
    medicalList.value.fieldList = data.fieldList;
  }
  const medicalFieldMap = new Map();
  if (fields) {
    fields.forEach((item: { fieldId: any }) => {
      medicalFieldMap.set(item.fieldId, item);
    });
    // 遍历data.fieldList并合并值
    data.fieldList.forEach((dataItem: { fieldId: any; fieldValue: any }) => {
      const medicalItem = medicalFieldMap.get(dataItem.fieldId);
      if (medicalItem) {
        // 追加fieldValue（可根据需要修改合并逻辑）
        if (
          medicalItem.fieldValue == null ||
          medicalItem.fieldValue === undefined ||
          medicalItem.fieldValue === '\n'
        ) {
          medicalItem.fieldValue = '';
          medicalItem.content = '';
        }
        if (dataItem.fieldValue == null || dataItem.fieldValue === undefined) {
          dataItem.fieldValue = '';
        }
        if (!medicalItem.fieldValue) {
          medicalItem.fieldValue += dataItem.fieldValue;
        } else {
          medicalItem.fieldValue += '，' + dataItem.fieldValue;
        }
        // 或者用数组形式保存多个值
        // medicalItem.fieldValue = [].concat(medicalItem.fieldValue, dataItem.fieldValue);
      }
    });
    medicalList.value.fieldList = fields;
  }

  const data1 = inspectionTableRef.value?.displayTableData;
  if (data1) {
    medicalList.value.examList = [
      ...data1,
      ...JSON.parse(JSON.stringify(data.examList)),
    ];
  }
  const data2 = inspectionTableRef.value?.displayTableData;

  medicalList.value.rxList = [
    ...medicalList.value.rxList,
    ...JSON.parse(JSON.stringify(data.rxList)),
  ];
  medicalList.value.rxList = renameRxList(medicalList.value.rxList);

  //   if (visitStatus1 == '1') {
  //   visitStatus.value = '1';
  // } else {
  //   visitStatus.value = '2';
  // }
  if (!isPlusSign.value) {
    if (visitStatus.value == '2') {
      medicalList.value.visitStatus = '2';
      visitStatus.value = '1';
    }
  }
  // ispatientData
  // if (medicalList.value.visitStatus == '2' && visitStatus.value == '1') {
  //   medicalList.value = data;
  // } else if (medicalList.value.visitStatus == '1') {
  //   medicalList.value = data;
  // } else {
  //   //ElMessage.error('当前不是编辑状态');
  // }
};
const onCopyIntm1 = (data: any, type: string) => {
  if (type == '1') {
    // 创建一个映射以便快速查找
    const fields = outpatientRef.value?.fields;
    //console.log(fields);

    if (fields) {
      const medicalFieldMap = new Map();
      if (medicalList.value.fieldList.length == 0) {
        medicalList.value.fieldList = data.fieldList;
      }
      fields.forEach((item: { fieldId: any }) => {
        medicalFieldMap.set(item.fieldId, item);
      });

      // 遍历data.fieldList并合并值
      data.fieldList.forEach((dataItem: { fieldId: any; fieldValue: any }) => {
        const medicalItem = medicalFieldMap.get(dataItem.fieldId);
        if (medicalItem) {
          // 追加fieldValue（可根据需要修改合并逻辑）
          if (
            medicalItem.fieldValue == null ||
            medicalItem.fieldValue === undefined ||
            medicalItem.fieldValue == '\n'
          ) {
            medicalItem.fieldValue = '';
            medicalItem.content = '';
          }
          if (
            dataItem.fieldValue == null ||
            dataItem.fieldValue === undefined
          ) {
            dataItem.fieldValue = '';
          }
          if (!medicalItem.fieldValue) {
            medicalItem.fieldValue += dataItem.fieldValue;
          } else {
            medicalItem.fieldValue += '，' + dataItem.fieldValue;
          }
          // 或者用数组形式保存多个值
          // medicalItem.fieldValue = [].concat(medicalItem.fieldValue, dataItem.fieldValue);
        }
      });
      //console.log(fields);
      medicalList.value.fieldList = fields;
    }
    // medicalList.value.fieldList = JSON.parse(JSON.stringify(data.fieldList));
  }
  if (type == '2') {
    // 合并两个数组
    // const data1 = dataProcess();
    // //console.log(data1);
    const data1 = inspectionTableRef.value?.displayTableData;
    data.examList.forEach((element: any) => {
      delete element.examId;
      delete element.payStatus;
    });
    if (data1) {
      medicalList.value.examList = [
        ...data1,
        ...JSON.parse(JSON.stringify(data.examList)),
      ];
    }
  }
  if (type == '3') {
    data.rxList.forEach((element: { rxId: any; payStatus: any }) => {
      delete element.rxId;
      delete element.payStatus;
    });
    //console.log(data.rxList);

    medicalList.value.rxList = [
      ...medicalList.value.rxList,
      ...JSON.parse(JSON.stringify(data.rxList)),
    ];

    medicalList.value.rxList = renameRxList(medicalList.value.rxList);
  }
  if (!isPlusSign.value) {
    if (visitStatus.value == '2') {
      medicalList.value.visitStatus = '2';
      visitStatus.value = '1';
    }
  }
};
// 保存模板
const onAddTemplate = async (data: any) => {
  // //console.log('保存模板数据:', data);
  //   const examList= fields.value.map((item: { fieldId: any; fieldValue: any; fieldImages: any;})=>{
  //   return {
  //     fieldId: item.fieldId,
  //     fieldValue: item.fieldValue,
  //     fieldImages: item.fieldImages,
  //   }
  // })
  // const data1 = {
  //   ...data,
  //   recomScene: '',
  //   fieldList: examList,
  // }
  // const result = await addTemplateMedical(data1);
  const data2 = dataProcess();
  if (data.templateCategory == '2') {
    const data1 = {
      ...data,
      templateCategory: data.templateType,
      templateType: data.templateType,
      examList: data2.examList,
    };
    const result = await addTemplateInspection(data1);
    if (result.code != '200') {
      //ElMessage.error(result.msg);
      return;
    }
  }
  if (data.templateCategory == '3') {
    const data1 = {
      ...data,
      templateCategory: data.templateType,
      templateType: data.templateType,
      rxList: data2.rxList,
    };
    const result = await addTemplatePrescription(data1);
    if (result.code != '200') {
      //ElMessage.error(result.msg);
      return;
    }
  }
  if (
    addTemplateRef.value &&
    typeof addTemplateRef.value.onclose === 'function'
  ) {
    addTemplateRef.value.onclose();
  }
  ElMessage.success('模板保存成功');
};
// 保存随访
const saveFollow = async () => {
  //console.log(followUpFormRef.value);
  const data1 = followUpFormRef.value?.patientDetail;
  data1.followupId = followupId.value;
  data1.attachmentUrls = followUpFormRef.value?.imgList
    ?.map((item) => item.url)
    .join(',');
  const data = await completeFollowup(data1);
  if (data.code != '200') {
    //ElMessage.error(data.msg);
    return;
  }
  ElMessage.success('随访完成');
  getFollowupListData();
  // onFollowup(followupId.value, patientId.value);
};
const formattedVisitDate = computed(() => {
  const val = formData.value.visitDate;
  if (!val) return '';
  const current = dayjs();
  const target = dayjs(val);
  if (!target.isValid()) return '';
  return target.isSame(current, 'day') ? '今天' : target.format('MM-DD');
});

// 选择模板
const onSelectTemplate = () => {
  isTemplate.value = true;
};
const yesterday = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() - 1);
  return date.toISOString().split('T')[0];
});
// 设置处方类型
// 方法
const setActiveType = (type: string) => {
  // activeType.value = type;
  // 构造不同类型的处方对象
  // 统计同类型数量

  const sameTypeCount =
    medicalList.value?.rxList?.filter(
      (i: { rxType: string }) => i.rxType === type
    ).length || 0;
  let newRx: any = {
    rxType: type,
    rxName: '',
    payStatus: null,
    payTime: null,
    storageId: storageList.value.find((item) => item.isDefault == 1)?.storageId,
    totalAmount: null,
    uuid: uuidv4(), // 唯一标识
  };
  switch (type) {
    case '1':
      newRx.rxName = `中西成药处方${toChineseNumber(sameTypeCount + 1)}`;
      //console.log(newRx.rxName);

      newRx.detailList = [];
      break;
    case '2':
      newRx.rxName = `输注处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.groupList = [
        {
          groupName: '第一组',
          usageCode: 'JMDZ',
          usageCodeText: '静脉滴注',
          frequencyCode: 'qd',
          frequencyCodeText: '1天1次',
          frequencyTimes: 1,
          cycle: 1,
          cycleUnit: 'day',
          cycleUnitText: '天',
          ivDripRate: '50',
          subtotal: 1000,
          uuid: uuidv4(),
          detailList: [],
        },
      ];
      break;
    case '3':
      newRx.rxName = `中药处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.tcmInfo = {
        frequencyCode: 'bid',
        frequencyCodeText: '1天2次',
        dailyDosage: '1',
        cycle: 7,
        cycleUnit: 'day',
        cycleUnitText: '天',
        usageCode: 'JFU',
        usageCodeText: '煎服',
        singleDosage: '200',
        remark: '',
        totalDoses: 0,
        subtotal: 0,
        detailList: [],
        uuid: uuidv4(), // 唯一标识
      };
      break;
    case '4':
      newRx.rxName = `外治处方${toChineseNumber(sameTypeCount + 1)}`;
      newRx.extInfo = {
        projectId: '',
        projectName: '',
        projectCategory: '',
        price: 0,
        projectType: '',
        frequencyCode: 'qd',
        frequencyCodeText: '1天1次',
        cycle: 1,
        cycleUnit: 'day',
        cycleUnitText: '天',
        remark: '',
        totalOutQty: '',
        totalOutQtyUnit: '',
        totalOutQtyUnitText: '',
        subtotal: '',
        detailList: [],
        uuid: uuidv4(), // 唯一标识
      };
      newRx.detailList = [];
      break;
  }
  medicalList.value?.rxList.push(newRx);
  //console.log(medicalList.value?.rxList);
};
const onSearchKeyboard = (value: string) => {
  displayNowUUid.value = value;
};
const onSave = (value: string) => {
  if (medicalList.value?.rxList?.length == 0) {
    //ElMessage.error('请先添加处方');
    return;
  }
  const type = {
    templateCategory: value,
    templateType: '1',
  };
  addTemplateRef.value?.open1(type);
};
//选择时间
const handleSearch = () => {
  if (selectedDate.value == 'today') {
    formData.value.visitDate = today.value;
  } else if (selectedDate.value == 'tomorrow') {
    formData.value.visitDate = tomorrow.value;
  } else if (selectedDate.value == 'yesterday') {
    formData.value.visitDate = yesterday.value;
  }
  formData.value.patientName = patientName.value;
  if (activeTab.value == 'follow') {
    getFollowupListData();
  } else {
    getMedicalListData();
  }
};
// 取消
const onCancel = () => {
  // isTemplate.value = false;
};
// 随访记录
const followupRecord = async () => {
  const params = {
    patientId: patientId.value,
    pageNo: 1,
    pageSize: 10000,
  };
  const response = await getFollowupRecordList(params);
  if (response.code == '200') {
    followupRecordList.value = response.data;
  }
};
const updataTemplate = (templates: any) => {
  //console.log(templates);
  templates.rxList.forEach((item: any) => {
    delete item.examId;
    delete item.rxId;
    item.uuid = uuidv4();
    item.storageId = storageList.value.find(
      (item) => item.isDefault == 1
    )?.storageId;
  });
  isTemplate.value = false;
  medicalList.value.rxList = [...medicalList.value.rxList, ...templates.rxList];

  // displayTableData.value = templates.detailList.map(
  //   (item: {
  //     projectCategory: string;
  //     price: number;
  //     subtotal: number;
  //     cycleUnit: string;
  //     totalOutQtyUnit: string;
  //   }) => ({
  //     ...item,
  //     projectCategoryName: useBaseDataStore.getEnumData(
  //       item.projectCategory,
  //       'projectCategoryEnum'
  //     ),
  //     priceNum: '￥' + (item.price / 100).toFixed(2), // 保留两位小数
  //     subtotalNum: '￥' + (item.subtotal / 100).toFixed(2),
  //     cycleUnitText: useBaseDataStore.getEnumData(
  //       item.cycleUnit,
  //       'cycleUnitEnum'
  //     ),
  //     totalOutQtyUnitText: useBaseDataStore.getDictsData(
  //       item.totalOutQtyUnit,
  //       'UNIT'
  //     ),
  //   })
  // );
};
const ondoctorAdvice = (value: any) => {
  medicalList.value.doctorAdvice = value;
};
onMounted(async () => {
  try {
    // const response = await getPatientList();
    // if (response && response.data) {
    //   patientList.value = response.data;
    //   if (patientList.value.length > 0) {
    //     patientId.value = patientList?.value[0]?.patientId || null; // 默认选中第一个患者
    //     onUserInfo(patientId.value);
    //   }
    // }
    // //console.log('患者列表:', response);
    formData.value.visitDate = dayjs().format('YYYY-MM-DD');
    //console.log(today.value);

    if (activeTab.value == 'follow') {
      getFollowupListData();
    } else {
      getMedicalListData();
    }
    followupRecord();
    // 如果数据还没有加载，则加载医疗记录字段数据
    if (!medicalFieldStore.isDataLoaded) {
      try {
        await medicalFieldStore.fetchMedicalRecordFields();
      } catch (error) {
        //console.error('加载医疗记录字段失败:', error);
        //ElMessage.error('加载医疗记录字段失败');
      }
    }
  } catch (error) {
    //console.error('获取患者列表失败:', error);
  }
});
const onCopys = (value: any) => {
  followDetail.value.followupResult = JSON.parse(JSON.stringify(value));
};
const getDispenseHistoryListApi = async (patientId: number) => {
  if (activeTab.value == 'dispense') {
    const res = await getDispenseHistoryList({
      patientId,
      pageNo: 1,
      pageSize: 10000,
    });

    if (res.code == '200') {
      dispenseHistoryList.value = res.data || [];
    } else {
    }
  } else {
    const res = await getDeliveryHistoryList({
      patientId,
      pageNo: 1,
      pageSize: 10000,
    });

    if (res.code == '200') {
      dispenseHistoryList.value = res.data || [];
    } else {
    }
  }
};
const onPatientAdd = () => {
  //console.log('添加新患者');
  patientUpdataRef.value?.open(); // 打开添加患者的弹窗
  // 这里可以添加跳转到添加患者页面的逻辑
};
// 随访列表
const getFollowupListData = async () => {
  const data = {
    pageNo: 1,
    pageSize: 10000,
    followupDate: formData.value.visitDate,
  };
  const res = await getFollowupList(data);
  if (res.code == '200') {
    // patientId.value = null;
    followupList.value = res.data;
    // followupId.value = null;
    if (res.data.length > 0) {
      followupId.value = res.data[0]?.followupId;
      onFollowup(res.data[0]);
    }

    //console.log('随访列表:', res.data);
  } else {
  }
};
const printBox = async () => {
  // medicalRecordPrintRef.value?.getHtml();
  //console.log(MedicalPrintinfo.value.uuid);
  setTimeout(() => {
    const data1 = medicalRecordPrintRef.value?.getHtml();
    const add: any[] = [];
    add.push(data1);
    //console.log(add);
    printMultiple({ printConfigs: add });
  });
};
const printBox1 = () => {
  // inspectPrintRef.value?.getHtml();
  setTimeout(() => {
    const data1 = inspectPrintRef.value?.getHtml();
    const add: any[] = [];
    add.push(data1);
    printMultiple({ printConfigs: add });
  });
};
// 打印多张
// printMultiple({
//   printConfigs: [printConfig, printConfig, printConfig],
// });
const printBox2 = async () => {
  const add: any[] = [];
  await nextTick();
  if (
    PrescriptionPrintInfo?.value &&
    PrescriptionPrintInfo?.value.rxList &&
    PrescriptionPrintInfo?.value.rxList.length > 0
  ) {
    //console.log(PrescriptionPrintInfo?.value);

    PrescriptionPrintInfo?.value.rxList.forEach((element: any) => {
      if (element.rxType == '1') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        //console.log(data1);

        add.push(data1);
      }
      if (element.rxType == '2') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        add.push(data1);
      }
      if (element.rxType == '3') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        add.push(data1);
      }
      if (element.rxType == '4') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        add.push(data1);
      }
    });
  }
  //console.log(add);

  printMultiple({ printConfigs: add });
  AdmissionsList.value = [1];
  if (
    memberCardRef?.value?.audioChunks &&
    memberCardRef?.value?.audioChunks.length > 0
  ) {
    Recording.value = [1];
  } else {
    Recording.value = [];
  }
  // prescriptionPrintRef.value?.getHtml();
};
const printBox3 = async () => {
  const add: any[] = [];
  await nextTick();
  if (AdmissionsList.value.indexOf(1) != -1) {
    //console.log(MedicalPrintinfo.value.uuid);
    add.push(medicalRecordPrintRef.value?.getHtml());
  }
  if (AdmissionsList.value.indexOf(2) != -1) {
    add.push(inspectPrintRef.value?.getHtml());
  }
  if (
    AdmissionsList.value.indexOf(3) != -1 &&
    PrescriptionPrintInfo?.value &&
    PrescriptionPrintInfo?.value.rxList &&
    PrescriptionPrintInfo?.value.rxList.length > 0
  ) {
    //console.log(PrescriptionPrintInfo?.value);

    PrescriptionPrintInfo?.value.rxList.forEach((element: any) => {
      if (element.rxType == '1') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        //console.log(data1);

        add.push(data1);
      }
      if (element.rxType == '2') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        add.push(data1);
      }
      if (element.rxType == '3') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        add.push(data1);
      }
      if (element.rxType == '4') {
        const data1 = {
          content: componentRefs.value[element.uuid]?.getHtml(element.uuid),
          styles: {
            pageSize: 'A5',
            margin: '0mm',
            customStyles: '',
          },
        };
        add.push(data1);
      }
    });
  }
  //console.log(add);
  if (add.length == 0) {
  } else {
    printMultiple({ printConfigs: add });
    AdmissionsList.value = [1];
    if (
      memberCardRef?.value?.audioChunks &&
      memberCardRef?.value?.audioChunks.length > 0
    ) {
      Recording.value = [1];
    } else {
      Recording.value = [];
    }
  }

  // prescriptionPrintRef.value?.getHtml();
};
const onPrint1 = async (item: any) => {
  //console.log(item);
  visiblePrint.value = true;

  try {
    // 并行发起所有请求
    const [data1, data2, data3] = await Promise.all([
      printMedicalRecord({ medicalId: item.medicalId, isAll: 1 }),
      printExam({ medicalId: item.medicalId, isAll: 1 }),
      printPrescription({ medicalId: item.medicalId, isAll: 1 }),
    ]);

    // 检查所有请求是否都成功
    const allSuccessful = [data1, data2, data3].every(
      (data) => data?.code === '200'
    );

    if (!allSuccessful) {
      // 收集失败的请求信息
      const failedRequests = [
        { name: '病历记录', data: data1 },
        { name: '检查报告', data: data2 },
        { name: '处方信息', data: data3 },
      ].filter((req) => req.data?.code !== '200');

      ElMessage({
        type: 'error',
        message: `以下请求未完成：${failedRequests
          .map((req) => `${req.name}(${req.data?.msg || '未知错误'})`)
          .join('、')}`,
      });
      return;
    }

    // 处理病历记录数据
    MedicalPrintinfo.value = {
      ...data1.data,
      uuid: uuidv4(),
    };
    //console.log(MedicalPrintinfo.value);

    // 处理检查报告数据
    inspectPrintInfo.value = {
      ...data2.data,
      uuid: uuidv4(),
    };

    // 处理处方数据
    PrescriptionPrintInfo.value = data3.data;
    if (!PrescriptionPrintInfo.value?.rxList?.length) {
      PrescriptionPrintInfo.value = [];
    } else {
      PrescriptionPrintInfo.value.rxList =
        PrescriptionPrintInfo.value.rxList.map((rxItem: any) => ({
          ...rxItem,
          ...PrescriptionPrintInfo.value,
          uuid: uuidv4(),
        }));
    }
    //console.log(PrescriptionPrintInfo.value);
  } catch (error) {
    // ElMessage({
    //   type: 'error',
    //   message: `请求发生异常：${error.message || '未知错误'}`
    // });
  }
};
// 格式化数据（仅返回指定精简字段）
const dataProcess = () => {
  const base = medicalList.value || {};
  const safeMap = (arr: any, fn: (x: any) => any) =>
    Array.isArray(arr) ? arr.map(fn) : [];

  // 规范化图片字段：数组/字符串 -> 标准化后的逗号分隔字符串
  const normalizeImages = (val: any): string => {
    if (Array.isArray(val))
      return val
        .map((s) => String(s).trim())
        .filter(Boolean)
        .join(',');
    if (typeof val === 'string')
      return val
        .split(',')
        .map((s) => s.trim())
        .filter((s) => !!s)
        .join(',');
    return '';
  };

  // 1) 病历字段最小化
  const fieldList = safeMap(outpatientRef.value?.fields, (f: any) => ({
    fieldId: f.fieldId,
    fieldValue: f.fieldValue,
    fieldImages: normalizeImages(f.fieldImages),
  }));

  // 2) 查验项目最小化
  const examList = safeMap(
    inspectionTableRef.value?.displayTableData,
    (it: any) => ({
      projectId: it.projectId,
      frequencyCode: it.frequencyCode,
      examId: it.examId || null,
      cycle: it.cycle,
      remark: it.remark,
      payStatus: it.payStatus,
      totalOutQty: it.totalOutQty,
    })
  );

  // 3) 处方/医嘱最小化（按 rxType 归一，优先取各子组件最新状态，通过 uuid 匹配）
  const findByUuid = <T>(
    list: T[] | undefined,
    pick: (x: T) => any,
    uuid: any
  ) => {
    if (!Array.isArray(list)) return undefined;
    return list.find((inst: any) => pick(inst)?.uuid === uuid);
  };

  const rxList = safeMap(base.rxList, (rx: any) => {
    const rxType = String(rx?.rxType || '');
    const uuid = rx?.uuid;
    let src: any = rx; // 兜底：使用 medicalList 中的对象
    //console.log(src, 'srcsrcsrcsrcsrc');

    if (rxType === '1') {
      const inst = findByUuid(
        prescriptionRef.value,
        (c: any) => c?.displayNow,
        uuid
      );
      if (inst?.displayNow) src = inst.displayNow;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxType: '1',
        payStatus: src.payStatus,
        rxId: src.rxId || null,
        detailList: safeMap(src.detailList, (d: any) => ({
          drugId: d.drugId,
          usageCode: d.usageCode,
          frequencyCode: d.frequencyCode,
          dosage: d.dosage,
          cycle: d.cycle,
          remark: d.remark,
          totalOutQty: d.totalOutQty,
        })),
      };
    }
    if (rxType === '2') {
      const inst = findByUuid(
        transfusionRef.value,
        (c: any) => c?.transfusionTableData,
        uuid
      );
      //console.log(inst, '输液处方实例');
      if (inst?.transfusionTableData) src = inst.transfusionTableData;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxId: src.rxId || null,
        rxType: '2',
        payStatus: src.payStatus,
        groupList: safeMap(src.groupList, (g: any) => ({
          groupName: g.groupName,
          usageCode: g.usageCode,
          frequencyCode: g.frequencyCode,
          cycle: g.cycle,
          ivDripRate: g.ivDripRate,
          detailList: safeMap(g.detailList, (d: any) => ({
            drugId: d.drugId,
            dosage: d.dosage,
            skinTest: d.skinTest,
            remark: d.remark,
            totalOutQty: d.totalOutQty,
          })),
        })),
      };
    }
    if (rxType === '3') {
      const inst = findByUuid(
        medicinalHerbRef.value,
        (c: any) => c?.externalTreatment,
        uuid
      );
      if (inst?.externalTreatment) src = inst.externalTreatment;
      return {
        storageId: src.storageId ?? null,
        rxName: src.rxName,
        rxId: src.rxId || null,
        rxType: '3',
        payStatus: src.payStatus,
        tcmInfo: {
          usageCode: src.tcmInfo?.usageCode,
          frequencyCode: src.tcmInfo?.frequencyCode,
          cycle: src.tcmInfo?.cycle,
          dailyDosage: src.tcmInfo?.dailyDosage,
          singleDosage: src.tcmInfo?.singleDosage,
          remark: src.tcmInfo?.remark,
          detailList: safeMap(src.tcmInfo?.detailList, (d: any) => ({
            drugId: d.drugId,
            dosage: d.dosage,
            decotionMethod: d.decotionMethod,
          })),
        },
      };
    }
    if (rxType === '4') {
      const inst = findByUuid(
        externalTreatmentRef.value,
        (c: any) => c?.externalTreatment,
        uuid
      );
      if (inst?.externalTreatment) src = inst.externalTreatment;
      return {
        rxName: src.rxName,
        rxId: src.rxId || null,
        rxType: '4',
        payStatus: src.payStatus,
        extInfo: {
          projectId: src.extInfo?.projectId,
          frequencyCode: src.extInfo?.frequencyCode,
          cycle: src.extInfo?.cycle,
          remark: src.extInfo?.remark,
          detailList: safeMap(src.extInfo?.detailList, (d: any) => ({
            acupointCode: d.acupointCode,
            sideType: d.sideType,
          })),
        },
      };
    }
    return null;
  }).filter(Boolean);

  // 4) 顶层患者字段（仅保留指定项）
  const systolicName = base.systolicName || '';
  const [sysFromName, diaFromName] = String(systolicName).split('/') as [
    string,
    string
  ];

  const data1: any = {
    medicalId: base.medicalId ?? medicalId.value ?? null,
    patientName: base.patientName ?? patientDetail.value?.patientName ?? '',
    patientPhone: base.patientPhone ?? patientDetail.value?.patientPhone ?? '',
    weight: base.weight ?? '',
    systolicBp: base.systolicBp ?? sysFromName ?? '',
    diastolicBp: base.diastolicBp ?? diaFromName ?? '',
    patientGender:
      base.patientGender ?? patientDetail.value?.patientGender ?? '',
    isFollowUp: base.isFollowUp ?? '1',
    followUpDays: base.followUpDays ?? undefined,
    doctorAdvice: base.doctorAdvice ?? '',
    ageMonth: base.ageMonth ?? '',
    ageYear: base.ageYear ?? '',
    fieldList,
    patientId: patientId.value,
    examList,
    rxList,
  };
  if (isPlusSign.value) {
    delete data1.medicalId;
  }
  if (base.isFollowUp == 0) {
    data1.followUpDays = null;
  }
  //console.log(data1, '最终数据');
  return data1;
};
// 获取主诉
const onZS = (value: string) => {
  medicalList.value.mainComplaint = value;
  ZSValue.value = outpatientRef.value?.fields.find(
    (f: any) => f.fieldCode === 'ZS'
  )?.fieldValue;
  const CBZD = outpatientRef.value?.fields.find(
    (f: any) => f.fieldCode === 'CBZD'
  )?.fieldValue;
  const ZHZD = outpatientRef.value?.fields.find(
    (f: any) => f.fieldCode === 'ZHZD'
  )?.fieldValue;
  // 构建结果字符串，只在有值时才添加逗号
  const resultParts = [];
  if (ZSValue.value) resultParts.push(ZSValue.value);
  if (CBZD) resultParts.push(CBZD);
  if (ZHZD) resultParts.push(ZHZD);

  return resultParts.join(',');
};
// 完成预诊
const onCompletePreDiagnosis = async () => {
  const data = dataProcess();
  const res = await completePreDiagnosis(data);
  if (res.code == '200') {
    ElMessage.success('预诊完成');
    isPlusSign.value = false;
    medicalId.value = res.data;
    getMedicalListData();
  } else {
  }
  //console.log(res);
};
const isAdmissionsEdit = ref(false);
const AdmissionsListEdit = ref([]);
//
const isMedicalValue = ref(false);
const handleSubmit2 = async () => {
  isMedicalValue.value = false;
  //console.log('提交');
  let data = dataProcess();
  data.medicalId = medicalId.value;
  const res = await drugConflictCheck(data);
  if (res.code == '200') {
    if (res.data.length > 0) {
      isMedical.value = true;
      riskList.value = res.data;
      isMedicalValue.value = true;
    } else {
      isMedical.value = false;
      const data = dataProcess();
      const res1 = await updateMedicalRecord(data);
      if (res1.code == '200') {
        ElMessage.success('门诊信息更新成功');
        visitStatus.value = '2';
        getMedicalDetailData();
        if (AdmissionsList.value.length > 0) {
          printData(res1.data);
        }
        isAdmissionsEdit.value = false;
      } else {
      }
    }
  }
  // const res = await updateMedicalRecord(data);
  // if (res.code == '200') {
  //   ElMessage.success('门诊信息更新成功');
  //   visitStatus.value = '2';
  //   getMedicalDetailData();
  //   printData(res.data);
  //   isAdmissionsEdit.value = false;
  // } else {
  // }
};
// 编辑门诊
const onCompletePreDiagnosisEdit = async () => {
  //console.log('编辑门诊');
  let data: any = dataProcess();
  //console.log(data);
  AdmissionsList.value = [];
  AdmissionsList.value.push(1);
  const dataPay = data.rxList.some((rx: any) => rx.payStatus != '2');
  if (dataPay) {
    AdmissionsList.value.push(3);
  }
  const dataPay1 = data.examList.some((rx: any) => rx.payStatus != '2');
  if (dataPay1) {
    AdmissionsList.value.push(2);
  }
  if (
    memberCardRef?.value?.audioChunks &&
    memberCardRef?.value?.audioChunks.length > 0
  ) {
    Recording.value = [1];
  } else {
    Recording.value = [];
  }
  //  Recording
  isAdmissionsEdit.value = true;
};
const isEdit = ref(false);
const isEdits = ref(true);
const handleSelect1 = (obj: any) => {
  isEdit.value = true;
  isEdits.value = false;
  patientId.value = obj.patientId;
  medicalList.value.ageYear = obj.ageYear;
  medicalList.value.ageMonth = obj.ageMonth;
  medicalList.value.patientGender = obj.patientGender;
  medicalList.value.patientName = obj.patientName;
  medicalList.value.idCard = obj.idCard;
  medicalList.value.patientPhone = obj.patientPhone;
  medicalList.value.weight = obj.weight;
  medicalList.value.patientId = obj.patientId;
  medicalList.value.systolicBp = obj.systolicBp;
  medicalList.value.diastolicBp = obj.diastolicBp;
  medicalList.value.systolicName =
    (obj.systolicBp ? obj.systolicBp : '') +
    '/' +
    (obj.diastolicBp ? obj.diastolicBp : '');
};
const onClearPatientInfo = () => {
  patientId.value = null;
  medicalList.value.ageYear = null;
  medicalList.value.ageMonth = null;
  medicalList.value.patientGender = null;
  medicalList.value.patientName = null;
  medicalList.value.idCard = null;
  medicalList.value.patientPhone = null;
  medicalList.value.weight = null;
  medicalList.value.systolicBp = null;
  medicalList.value.diastolicBp = null;
  isEdit.value = false;
  isEdits.value = false;
};
// 接诊打印
const printData = async (medicalId: any) => {
  if (Recording.value.length > 0) {
    memberCardRef?.value?.onToggleRecordingxiazai();
  }
  try {
    // 并行发起所有请求
    const [data1, data2, data3] = await Promise.all([
      printMedicalRecord({ medicalId: medicalId }),
      printExam({ medicalId: medicalId }),
      printPrescription({ medicalId: medicalId }),
    ]);

    // 统一错误检查（任一接口失败则终止）
    if (data1.code !== '200' || data2.code !== '200' || data3.code !== '200') {
      const errorMsg =
        data1.code !== '200'
          ? data1.msg
          : data2.code !== '200'
          ? data2.msg
          : data3.msg;
      // ElMessage({ type: 'error', message: errorMsg });
      return;
    }

    // 数据处理
    MedicalPrintinfo.value = {
      ...data1.data,
      uuid: uuidv4(),
    };

    inspectPrintInfo.value = {
      ...data2.data,
      uuid: uuidv4(),
    };

    PrescriptionPrintInfo.value =
      data3.data?.rxList?.length > 0
        ? {
            ...data3.data,
            rxList: data3.data.rxList.map((item: any) => ({
              ...item,
              ...data3.data,
              uuid: uuidv4(),
            })),
          }
        : [];

    // 打印前调试输出
    //console.log('AdmissionsList:', PrescriptionPrintInfo.value);
    //console.log('All data ready, start printing...');

    // 执行打印
    printBox3();
  } catch (error) {
    // ElMessage({
    //   type: 'error',
    //   message: `系统错误: ${
    //     error instanceof Error ? error.message : String(error)
    //   }`,
    // });
  }
};
const onPrint = async () => {
  visiblePrint.value = true;

  try {
    // 使用Promise.all并行请求三个接口
    const [data1, data2, data3] = await Promise.all([
      printMedicalRecord({ medicalId: medicalId.value, isAll: 1 }),
      printExam({ medicalId: medicalId.value, isAll: 1 }),
      printPrescription({ medicalId: medicalId.value, isAll: 1 }),
    ]);

    // 检查每个请求的返回状态
    const allSuccessful = [data1, data2, data3].every(
      (data) => data?.code === '200'
    );
    if (!allSuccessful) {
      const failedMessages = [data1, data2, data3]
        .filter((data) => data?.code !== '200')
        .map((data) => data?.msg || '未知错误');

      ElMessage({
        type: 'error',
        message: `部分请求未完成：${failedMessages.join('; ')}`,
      });
      return;
    }

    // 处理medicalRecord数据
    MedicalPrintinfo.value = {
      ...data1.data,
      uuid: uuidv4(),
    };

    // 处理exam数据
    inspectPrintInfo.value = {
      ...data2.data,
      uuid: uuidv4(),
    };

    // 处理prescription数据
    PrescriptionPrintInfo.value = data3.data;
    if (
      PrescriptionPrintInfo.value == null ||
      PrescriptionPrintInfo.value.rxList.length == 0
    ) {
      PrescriptionPrintInfo.value = [];
    } else {
      PrescriptionPrintInfo.value.rxList =
        PrescriptionPrintInfo.value.rxList.map((item: any) => ({
          ...item,
          ...PrescriptionPrintInfo.value,
          uuid: uuidv4(),
        }));
    }

    //console.log(PrescriptionPrintInfo.value);

    // 如果需要调用打印方法可以在这里执行
    // medicalRecordPrintRef.value?.onPrintQRCode();
    // inspectPrintRef.value?.onPrintQRCode();
  } catch (error) {
    // ElMessage({
    //   type: 'error',
    //   message: `请求发生错误：${error.message || '未知错误'}`
    // });
  }
};
const onReceivingPatients = async () => {
  //console.log('完成接诊');
  let data: any = dataProcess();
  //console.log(data);
  AdmissionsList.value = [];
  AdmissionsList.value.push(1);
  const dataPay = data.rxList.some((rx: any) => rx.payStatus != '2');
  if (dataPay) {
    AdmissionsList.value.push(3);
  }
  const dataPay1 = data.examList.some((rx: any) => rx.payStatus != '2');
  if (dataPay1) {
    AdmissionsList.value.push(2);
  }
  if (
    memberCardRef?.value?.audioChunks &&
    memberCardRef?.value?.audioChunks.length > 0
  ) {
    Recording.value = [1];
  } else {
    Recording.value = [];
  }
  isAdmissions.value = true;
};
const handleSubmit1 = async () => {
  const data = dataProcess();
  const res = await drugConflictCheck(data);
  if (res.code == '200') {
    if (res.data.length > 0) {
      isMedical.value = true;
      riskList.value = res.data;
      isAdmissions.value = false;
    } else {
      isMedical.value = false;
      const data = dataProcess();
      const resCode = await completeInquiry(data);
      if (resCode.code == '200') {
        ElMessage.success('接诊完成');
        isMedical.value = false;
        isPlusSign.value = false;
        if (AdmissionsList.value.length > 0) {
          printData(resCode.data);
        }
        isAdmissions.value = false;
        getMedicalListData();
      } else {
      }
    }
    // ElMessage.success('接诊完成');
  } else {
  }
};
const handleSubmit = async () => {
  const data = dataProcess();
  if (isMedicalValue.value) {
    const res = await updateMedicalRecord(data);
    if (res.code == '200') {
      ElMessage.success('门诊信息更新成功');
      visitStatus.value = '2';
      getMedicalDetailData();
      if (AdmissionsList.value.length > 0) {
        printData(res.data);
      }
      isAdmissionsEdit.value = false;
      isMedical.value = false;
    } else {
    }
  } else {
    const res = await completeInquiry(data);
    if (res.code == '200') {
      ElMessage.success('接诊完成');
      isMedical.value = false;
      if (AdmissionsList.value.length > 0) {
        printData(res.data);
      }
      medicalId.value = res.data;
      isPlusSign.value = false;
      getMedicalListData();
    } else {
    }
  }
};
// 获取患者列表
const getMedicalListData = async () => {
  const res = await getMedicalList({
    pageNo: 1,
    pageSize: 10000,
    ...formData.value,
  });
  if (res.code == '200') {
    patientList.value = res.data;

    if (medicalId.value) {
      if (res.data.length == 0) {
        patientId.value = null;
        return;
      }
      const data = res.data.find(
        (item: any) => item.medicalId == medicalId.value
      );
      patientId.value = data.patientId;
      onUserInfo(data.patientId, medicalId.value, data.visitStatus);
    } else {
      if (res.data.length == 0) {
        patientId.value = null;
        return;
      }
      onUserInfo(
        patientList.value[0].patientId,
        patientList.value[0].medicalId,
        patientList.value[0].visitStatus
      );
    }

    // if (medicalId.value) {
    //   if (res.data.length == 0) {
    //     patientId.value = null;
    //     return;
    //   }
    //   const data = res.data.find(
    //     (item: any) => item.medicalId == medicalId.value
    //   );

    // }
    //console.log('诊室列表:', res.data);
  } else {
  }
};
</script>

<style scoped lang="scss">
::v-deep(.el-input__wrapper) {
  padding-left: 5px !important;
  padding-right: 5px !important;
}

.register-date-custom-picker {
  position: absolute;
  top: 33px;
  z-index: 10;
  background: #fff;
  box-shadow: 0px 5px 5px -3px rgba(0, 0, 0, 0.1),
    0px 8px 10px 1px rgba(0, 0, 0, 0.06), 0px 3px 14px 2px rgba(0, 0, 0, 0.05);
  width: 100%;
}

.line {
  width: 0px;
  height: 23px;
  border: 1px solid #dcdcdc;
  margin-right: 10px;
}

// ::v-deep(.custom-transition-dialog-2) {
//   padding: 0 !important;
//   .el-dialog__header {
//     padding: 0 !important;
//   }
// }
::v-deep(.custom-transition-dialog-2) {
  padding: 0 !important;
}

::v-deep(.custom-transition-dialog-2 > .el-dialog__header) {
  padding: 0 !important;
}

.risk-dialog-body {
  padding: 12px 16px 4px 16px;
  max-height: 50vh;
  overflow: auto;
}

.risk-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  color: #d93026;
  /* 红色提示 */
  font-size: 14px;
  line-height: 22px;
  padding: 6px 0;
  border-bottom: 1px solid #eee;
}

.risk-icon {
  color: #d93026;
  font-size: 18px;
  margin-top: 2px;
}

.risk-text {
  flex: 1;
}

.risk-empty {
  color: rgba(0, 0, 0, 0.45);
  text-align: center;
  padding: 16px 0;
}

.search-container-box {
  height: calc(100% - 235px);
  overflow: auto;
}

.patient-container {
  padding: 10px;
  height: calc(100% - 55px);
  overflow: auto;

  .search-container {
    display: flex;
    gap: 7px;
    align-items: center;
    margin-bottom: 10px;
    position: relative;

    .search-input {
      flex: 1;
      width: 182px;
    }

    .date-select {
      width: 48px;
    }
  }
}

.patient-header {
  display: flex;
  align-items: center;
  position: relative;
  width: 100%;
  padding: 10px;
  border-bottom: 1px solid #e7e7e7;

  .patient-title {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-color-primary);
  }

  .patient-line {
    position: absolute;
    width: 30px;
    top: 41px;
    height: 2px;
    background-color: var(--el-color-primary);
    margin-top: 4px;
  }
}

.user-info-container {
  background-color: #f0f0f0;
  padding: 10px;
}

.user-info-active {
  background: rgba(24, 179, 171, 0.1);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid var(--el-color-primary);
}

.user-info—box {
  padding: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 5px;
  cursor: pointer;

  .user-info.selected {
    background-color: #bce8f1;
  }

  .avatar {
    width: 16px;
    height: 16px;
  }

  .name {
    font-size: 15px;
  }

  .dropdown-icon {
    margin-left: auto;
  }

  .phone-number {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 13px;
    color: rgba(0, 0, 0, 0.4);
    line-height: 22px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    // margin-left: 10px;
  }

  .age {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.4);
  }

  .status-info {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #ff8c00;
    display: inline-block;
  }

  .status-text {
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 14px;
    // font-weight: 600;
  }
}

::v-deep(.el-tabs__item) {
  width: 70px !important;
  /* 设置每个tab的宽度 */
  padding: 0 !important;
  /* 去除默认padding */
}

.recent-visit {
  padding-bottom: 10px;
  margin: 0 auto;
  text-align: right;
}

.sidebar-tabs {
  flex-shrink: 0;
  display: flex;
  gap: 24px;
  height: 52px;
  padding-left: 22px;
  border: 1px solid #e7e7e7;

  .tab-btn {
    cursor: pointer;
    font-weight: 400;
    font-size: 20px;
    color: rgba(0, 0, 0, 0.4);
    line-height: 52px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    position: relative;

    &.active {
      font-weight: 400;
      font-size: 20px;
      color: #18b3ab;
      text-align: left;
      font-style: normal;
      text-transform: none;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background: #18b3ab;
      }
    }
  }
}
</style>
<style lang="scss">
.date-select {
  .el-select__wrapper {
    border: none !important;
    box-shadow: none !important;
    background-color: transparent !important;
    padding: 0 !important;
  }

  .el-input__inner {
    color: var(--el-color-primary) !important;
    font-weight: 500 !important;
  }

  // 设置后缀图标颜色为黑色
  .el-icon {
    color: #000 !important;
  }
}

.header-section-1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0px 0 0;
  padding: 12px 20px;
  background: #ffffff;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;

  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .action-buttons {
    display: flex;
    align-items: center;

    .el-button.active {
      background-color: #409eff;
      color: white;
      border-color: #409eff;
    }
  }
}

.patient-info-bar-1 {
  display: flex;
  align-items: center;
  background: #f8fafb;
  border-radius: 6px;
  box-sizing: border-box;
  justify-content: space-between;
  padding-bottom: 10px;
  position: relative;
}

.patient-info-bar {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 6px;
  padding: 8px 16px;
  box-sizing: border-box;

  .info-input {
    width: 90px;
    margin-right: 0;
    background: transparent;

    .el-input__wrapper {
      background: transparent;
      border: none;
      box-shadow: none;
      padding: 0 8px;
    }

    input {
      background: transparent;
      border: none;
      box-shadow: none;
      font-size: 15px;
      color: #333;
      padding: 0;
    }
  }

  .name-input {
    width: 70px;
  }

  .age-input,
  .month-input {
    width: 60px;
  }

  .weight-input {
    width: 80px;
  }

  .bp-input {
    width: 110px;
  }

  .unit {
    color: #bbb;
    font-size: 15px;
    margin: -2px 4px 0 0;
    color: #000000;
  }

  .divider {
    width: 1px;
    height: 28px;
    background: #e5e6eb;
    margin: 0 10px;
  }

  .gender-group {
    margin: 0 8px 0 0;

    .el-radio-button__inner {
      border: none;
      background: transparent;
      color: #333;
      font-size: 15px;
      padding: 0 12px;
    }

    .el-radio-button__orig-radio:checked + .el-radio-button__inner {
      background: #fff;
      color: #18b3ab;
      border-radius: 4px;
      box-shadow: 0 0 0 1px #18b3ab;
    }
  }

  .btn-group {
    display: flex;
    align-items: center;
    margin-left: 16px;
    gap: 8px;

    .el-button {
      min-width: 90px;
      font-size: 15px;
      border-radius: 4px;
      padding: 0 18px;
    }

    .el-button--primary {
      background: #18b3ab;
      border-color: #18b3ab;
    }
  }
}
</style>

<!-- 复刻“是否随访/医嘱事项”卡片样式 -->
<style lang="scss" scoped>
.printBtn {
  width: 296px;
  cursor: pointer;
  line-height: 46px;
  background: rgba(220, 220, 220, 0.1);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #ebebeb;
  text-align: center;
  font-weight: 400;
  font-size: 16px;
  color: #16ada4;
}

.printBtn:hover {
  border: 1px solid rgba(22, 173, 164, 0.48);
  background: rgba(22, 173, 164, 0.08);
}

.followup-box {
  background: #fff;
  border: 1px solid #e7e7e7;
  border-radius: 12px;
  // overflow: hidden;
  margin-top: 10px;
  /* 卡片与周围间距按需放开 */
  /* margin-top: 10px; */

  .followup-row {
    display: flex;
    align-items: center;
    min-height: 52px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .followup-label {
      width: 110px;
      padding: 0 14px;
      color: #666;
      font-size: 14px;
      box-sizing: border-box;
      flex-shrink: 0;
      text-align: center;
    }

    .followup-content {
      flex: 1;
      border-left: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px 16px;
      box-sizing: border-box;

      /* 选项组：不随访/随访 */
      .visit-options {
        display: flex;
        align-items: center;
        gap: 12px;

        .visit-option {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 6px 10px;
          border-radius: 6px;
          border: 1px solid transparent;
          cursor: pointer;
          color: #333;
          transition: all 0.15s ease-in-out;

          .icon-box {
            width: 18px;
            height: 18px;
            border-radius: 4px;
            background: #fff;
            border: 1px dashed #cfd4da;
            /* 未选中虚线框 */
            position: relative;
            flex-shrink: 0;
          }
        }
      }

      /* 医嘱事项输入，贴合行高且无强阴影 */
      .advice-input {
        width: 100%;

        :deep(.el-input__wrapper) {
          background: transparent;
          box-shadow: none;
          border: none;
          padding: 0;
          height: 36px;
        }

        :deep(input) {
          height: 36px;
        }
      }
    }
  }
}

.register-date-box {
  cursor: pointer;
  text-align: right;
}

.register-date-custom-picker {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 2000;
  margin-top: 4px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 8px 8px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}
</style>
